from pyglet.media import StaticSource, Player, load

class SoundSystem():
	"""
	Class used to manage sounds.
	"""

	def __init__(self, num_players):
		self.players = []
		for i in range(num_players):
			self.players.append(CGPlayer())
			self.players[i].eos_action = Player.EOS_NEXT
			self.players[i].play()
			
		self.loop_player = CGPlayer(loop=True)
		self.loop_player.play()
			
		self.sounds = {}
		
	def load(self, name, file):
		self.sounds[name] = StaticSource(load(file))
		
	def load_stream(self, name, file):
		self.sounds[name] = load(file)
		
	def play(self, name):
		for player in self.players:
			if player.available:
				player.available = False
				player.queue(self.sounds[name])
				break
			
	def play_loop(self, name):
		if self.loop_player.source is None:
			self.loop_player.queue(self.sounds[name])
		elif self.loop_player.source == self.sounds[name]:
			return
		else:
			# TODO: Any better way to do this?
			self.loop_player.pause()
			self.loop_player.eos_action = Player.EOS_NEXT
			self.loop_player.queue(self.sounds[name])
			self.loop_player.seek(self.loop_player.source.duration)
			self.loop_player.play()
			
	def volume(self, volume):
		for player in self.players:
			player.volume = volume
			
	def volume_loop(self, volume):
		self.loop_player.volume = volume
			
class CGPlayer(Player):
	def __init__(self, loop=False):
		super(CGPlayer, self).__init__()
		
		self.available = True
		self.loop = loop
		if loop:
			self.eos_action = Player.EOS_LOOP
		
	def on_eos(self):
		self.available = True
		
		if self.loop:
			self.eos_action = Player.EOS_LOOP